package com.atguigu.paymentdemo.controller;

import com.atguigu.paymentdemo.entity.WxUser;
import com.atguigu.paymentdemo.service.WxUserService;
import com.atguigu.paymentdemo.util.HttpUtils;
import com.atguigu.paymentdemo.vo.R;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;

@CrossOrigin//开放前端的跨域访问
@Api(tags = "微信用户")
@RestController
@RequestMapping("wxUser")
public class WxUserController {

    @Resource
    private WxUserService wxUserService;

    private String wx_appid = "wxd9c30ef6299618da";
    private String wx_appsecret = "f5b17d5e1d58249e60ee2b6cdb99ffe9";
    private String accesstokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
    private String refreshUrl ="https://api.weixin.qq.com/sns/oauth2/refresh_token";

    /**
     * 公众号授权登录
     * @param code
     * @param state
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @ApiOperation("公众号登录")
    @GetMapping("wxLogin")
    public R wxLogin(String code, String state, HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("--------------------登陆认证对比开始----------------------");
        //第一步用户同意授权，获取code
        System.out.println("第一步获取code值："+ code);
        //第二步通过code换取网页授权access_token
        System.out.println("第二步通过code换取网页授权access_token值：");
        String accesstokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
        accesstokenUrl += "?appid="+wx_appid;
        accesstokenUrl += "&secret="+wx_appsecret;
        accesstokenUrl += "&code=" + code;
        accesstokenUrl += "&grant_type=authorization_code";
        System.out.println("第一步URl=====:"+accesstokenUrl);
        JSONObject jsonObject = HttpUtils.doGetJson(accesstokenUrl);
        String openId = "";
        try{
            openId = jsonObject.getString("openid");
        }catch (Exception e){
            throw new RuntimeException("获取openid异常");
        }
        String access_Token = jsonObject.getString("access_token");
        //返回token结果
        System.out.println("access_token ="+ access_Token);
        System.out.println("openId ="+ openId);

        //第三步刷新access_token（如果需要）
        System.out.println("第三步刷新access_token（如果需要）：");
        String refreshUrl ="https://api.weixin.qq.com/sns/oauth2/refresh_token";
        refreshUrl +="?appid="+wx_appid;
        refreshUrl +="&grant_type=refresh_token";
        refreshUrl +="&refresh_token="+access_Token;//获取第二步的refresh_token后，请求以下链接获取access_token： c
        JSONObject refreshJSON = HttpUtils.doGetJson(refreshUrl);
//        String access_Token = jsonObject.getString("access_token");
        System.out.println("refreshJSON ="+ refreshJSON);

        //第四步拉取用户信息(需scope为 snsapi_userinfo)
        System.out.println("第四步拉取用户信息(需scope为 snsapi_userinfo)：");
        String userUrl="https://api.weixin.qq.com/sns/userinfo";
        userUrl +="?access_token="+access_Token;//获取第二步中access_token
        userUrl +="&openid="+ openId;//获取第二步中的openid
        userUrl +="&lang=zh_CN";
        JSONObject userJSONObj = HttpUtils.doGetJson(userUrl);
        System.out.println("userResponse ="+ userJSONObj.toString());
        //解析数据出来，返回字段注解：https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#2
        //第四步那里

        //模拟登陆将这里将状态改为认证了
        String userOpenId = userJSONObj.getString("openid");
        // 获取openid
        System.out.println("openid:"+userOpenId);

        //保存微信授权的用户信息
        Cookie cookie = new Cookie("openid", userOpenId);
        cookie.setPath("/");
        //cookie.setDomain("wvng2j42.dongtaiyuming.net");
//        cookie.setDomain("*");
        cookie.setMaxAge(60 * 5);
        response.addCookie(cookie);
        //response.sendRedirect(state);

        WxUser wxUser = new WxUser();
        // 判断用户openID是否存在
        if(StringUtils.isBlank(openId)) {
            throw new RuntimeException("授权失败");
        }else{
            WxUser wxUserByOpenid = wxUserService.getWxUserByOpenid(openId);
            if(wxUserByOpenid != null){
                wxUser.setOpenId(userOpenId);
                wxUserService.updateById(wxUser);
            }else{
                String nickName = userJSONObj.getString("nickname");
                wxUser.setNickName(nickName);
                String headimgurl = userJSONObj.getString("headimgurl");
                wxUser.setHeadimgUrl(headimgurl);
                wxUser.setOpenId(openId);
                wxUser.setCreateTime(new Date());
                wxUserService.save(wxUser);
            }
            wxUser = wxUserService.getWxUserByOpenid(openId);
        }
        return R.ok().data("data",wxUser);
    }

    /**
     * 获取用户信息
     * @param id
     * @return
     */
    @GetMapping("/getByById")
    public R list(Integer id){
        WxUser wxuser = wxUserService.getById(id);
        return R.ok().data("data",wxuser);
    }
}
